package com.dingding.transfer.stamper.listener;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dingding.transfer.stamper.constant.RabbitConstants;
import com.dingding.transfer.stamper.dao.StampRecordDao;
import com.dingding.transfer.stamper.dto.BaseResult;
import com.dingding.transfer.stamper.entity.StampRecord;
import com.dingding.transfer.stamper.entity.UseStampRecord;
import com.dingding.transfer.stamper.handler.DelayMessageSenderFactory;
import com.dingding.transfer.stamper.service.BusinessService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author wangxiyuan
 * @description
 * @createDate 2021/4/8 13:51
 **/
@Component
@Slf4j
public class DelayMessageListener {
    @Autowired
    private StampRecordDao stampRecordDao;

    @Autowired
    private BusinessService businessService;

    private static final Map<String,Integer> map = new ConcurrentHashMap<>();

    @RabbitListener(queues = RabbitConstants.Queue.DELAY_QUEUE_NAME)
    public void handle(String message) {
        log.info("接受消息{}并进行处理",message);
        boolean reportStatus = false;
        List<UseStampRecord> stampRecords = stampRecordDao.findStampRecords(message);
        try {
            if(CollectionUtil.isNotEmpty(stampRecords)){
                // 如果最新的记录距离当前时间超过了10秒，则预估印章记录已经同步完毕，如果没有，则仍在同步中，则下次消费 DateTimeFormatter.ofPattern
                String time = DateUtil.format(stampRecords.get(0).getUseTime(), "yyyy-MM-dd HH:mm:ss");
                if(LocalDateTime.now().minusSeconds(10).isAfter(LocalDateTime.parse(time, DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")))){
                    BaseResult baseResult = businessService.reportStampRecord(stampRecords);
                    if(CollectionUtil.isNotEmpty(stampRecords) && baseResult.isSuccess()){
                        reportStatus = true;
                        stampRecords.forEach(stampRecord -> {
                            stampRecordDao.update(null,new UpdateWrapper<StampRecord>()
                                    .eq("serial_id",stampRecord.getSerialId()).set("status",true));
                        });
                    }
                }
            }
        } catch (Exception e) {
            log.error("报送过程中出现错误{}",e.getMessage());
        }
        if(!reportStatus){
            synchronized (map){
                Integer num = map.get(message);
                if(num != null && num < 5){
                    DelayMessageSenderFactory.DelayMessageSender instance = DelayMessageSenderFactory.getInstance();
                    instance.sendDelayMessage(message,60000);
                    map.put(message,++num);
                }else if(num == null){
                    map.put(message,1);
                }else{
                    log.info("处理了5次仍然不能报送记录，将消息{}丢弃",message);
                }
            }
        }
    }
}
